package com.cyx.netty.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/*
异步IO 示例
 */
@Slf4j
public class AioFileChannel {
    public static void main(String[] args) {
        try {
            AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("netty-study\\src\\main\\resources\\data.txt"), StandardOpenOption.READ);
            // 参数1 ByteBuffer
            // 参数2 读取的其实位置
            // 参数3 附件
            // 参数4 回调对象CompletionHandler
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.info("read start ...");
            // channel.read 异步
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override // read成功
                public void completed(Integer result, ByteBuffer attachment) {
                    log.info("read completed ... 读到的字节数：{}", result);
                    attachment.flip();
                    out(attachment);
                }

                @Override // read失败
                public void failed(Throwable exc, ByteBuffer attachment) {

                }
            });
            log.info("read end ...");
            Thread.sleep(100); // 防止主线程直接结束
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void out(ByteBuffer buffer) {
        while (buffer.hasRemaining()) {
            byte b = buffer.get();
            System.out.print(((char) b));
        }
    }
}
